<script setup lang='ts'>
import { ref,reactive,watch, nextTick, markRaw } from 'vue'
import * as echarts from 'echarts'
import type { TabsPaneContext } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  GetLineChartHyperTemperShock

} from '@/api/publicApi'
import setUpTime from '@/utils/setUpTime'
// 控制弹框
const dialogVisible = ref(false)
const formVisible = ref(false)
// 点击的某项
let showItem:any = reactive({})
// 控制tab
const activeName = ref('first')

// 策略数据
const fromList = reactive({
  positionDescription: '',
  maxValue1: '',
  sensorType: '',
  maxValue2: ''
})
// 表单验证规则
const rules = reactive({
  sensorType: [
    { required: true, message: '请选择测点类型', trigger: 'change' }
  ],
  name: [ { required: true, message: '请输入测点名称', trigger: 'blur' } ],
  maxValue1: [
    { required: true, message: '请输入一级报警值', trigger: 'blur' }
  ],
  maxValue2: [
    { required: true, message: '请输入二级报警值', trigger: 'blur' }
  ]
})

// 传感器类型源数据
const sensorTypeList = ref([
  {
    name: '温度',
    value: 'wendu'
  },
  {
    name: '振动',
    value: 'zhendong'
  }
])

// 区分添加还是修改
const isAdd = ref(true)
// 历史数据筛选时间
const time = ref([ '','' ])
// 表格
const tableData = [
  {
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-02',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-04',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  }
]

const cellStyle = {
  textAlign: 'center'
}

const headStyle = {
  textAlign: 'center'
}

// tab2
// ref
const chart1 = ref()
const chart2 = ref()
const myEcharts = echarts
// 表单验证
const coverRules = {
  start: [ { required: true, message: '请选择开始时间', trigger: 'blur' } ],
  end: [ { message: '请选择结束时间', trigger: 'blur' } ]
}

// 表单参数
const formData = reactive({
  BarWheelMachineCode: '',
  code: null,
  measurePointCode: null,
  time: [ '','' ],
  sensorType: '',
  Type: 20, //查询类型（10avg; 20:max; 30:min）
  timeInterval: 30 //时间间隔（目前仅支持5，10，30）
})
// 是否展示更多筛选条件
const isMore = ref(false)
// 查询类型
const searchTypeList = [
  {
    id: 10,
    type: '平均值'
  },
  {
    id: 20,
    type: '最大值'
  },
  {
    id: 30,
    type: '最小值'
  }
]
// 时间间隔列表
const timeIntervalList = [
  {
    title: '5分钟',
    value: 5
  },
  {
    title: '10分钟',
    value: 10
  },
  {
    title: '30分钟',
    value: 30
  }
]
// 图表数据
const seriesList: any = ref([])
// x轴坐标
let timeList: any = ref([])
// 温度数据
let temperValueList:any = ref([])
// 振动数据
let shockValueList: any = ref([])

// echarts图表option
const option = reactive( {
  title: {
    text: 'Stacked Line'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: [ 'Email' ]
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: 'Email',
      type: 'line',
      stack: 'Total',
      data: [ -12, -13, -10, -13, -9, -23, -21 ],
      smooth: true,
      lineStyle: {
        color: '#5470C6',
        width: 2,
        type: 'dashed'
      }
    }
  ]
})

// 定义函数
// 展示弹框
const showDialog = (row: any,type?:any) => {
  showItem = {}
  showItem = { ...row }
  dialogVisible.value = true
}
// 点击切换tab
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

// 展示修改弹框
const showFormDialog = (type:number,row?:any) => {
  if(type) {
    isAdd.value = false
    console.log('编辑某项---->',row)
  } else {
    isAdd.value = true
  }
  formVisible.value = true
}

// 删除策略
const deleteItem = (row:any) => {
  ElMessageBox.confirm(
    '确定要删除该策略?',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      console.log('确认删除---->', row)
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 确定
const determine = () => {
  console.log('查询------->')
  
}

// 取消
const cancellation = () => {
  console.log('查询------->')
  formVisible.value = false
}

// tab2函数
watch(activeName,(nv,ov) => {
  if(nv === 'second') {
    initEcharts()
  }else {
    coverChartResize()
  }
})
// 查询
const queryInfo = () => {
  seriesList.value = []
  getHistoryList()
}

// 获取历史数据
const getHistoryList = () => {
  // 折线图g
  let param = {
    BarWheelMachineCode: localStorage.BarWheelMachineCode
      ? localStorage.BarWheelMachineCode
      : null, //堆取料机编号
    DeviceCode: showItem.deviceCode, // 设备编号
    // QueryDataType: showItem.deviceCode, // 设备编号
    MeasurePointCode: showItem.measurePointCode, //测点编号
    MinCreationTime: formData.time[0] , //最小采集时间
    MaxCreationTime: formData.time[1] , //最大采集时间
    QueryType: formData.Type, //查询类型（10avg; 20:max; 30:min）
    TimeInterval: formData.timeInterval //时间间隔（目前仅支持5，10，30）
  }
  GetLineChartHyperTemperShock(param).then(res => {
    let list = res.result

    timeList.value = []
    temperValueList.value = []
    shockValueList.value = []

    shockValueList.value.push({
      name: showItem.positionDescription + '(m/s²)',
      data: [],
      type: 'line',

      lineStyle: {
        width: 2,
        type: 'dashed'
      },
      emphasis: {
        lineStyle: {
          width: 2 // hover时的折线宽度
        }
      }
    })
    temperValueList.value.push({
      name: showItem.positionDescription + '(°C)',
      data: [],
      type: 'line',

      lineStyle: {}
    })
    for (let i = 0; i < list.values.length; i++) {
      //温度值
      temperValueList.value[0].data.push(list.values[i].temperValue)

      shockValueList.value[0].data.push(list.values[i].shockValue)
      // X轴的时间点
      if (timeList.value.length < list.values.length) {
        timeList.value.push(setUpTime.formatTime(list.values[i].id))
      }
    }

    initEcharts()
  })
}

// 导出数据
const exportXlsx = type => {
  let param = {
    BarWheelMachineCode: localStorage.BarWheelMachineCode
      ? localStorage.BarWheelMachineCode
      : null, //堆取料机编号
    DeviceCode: showItem.deviceCode, // 设备编号
    MeasurePointCode: showItem.measurePointCode, //测点编号
    MinCreationTime: formData.time[0], //最小采集时间
    MaxCreationTime: formData.time[1], //最大采集时间
    QueryType: formData.Type, //查询类型（10avg; 20:max; 30:min）
    TimeInterval: formData.timeInterval, //时间间隔（目前仅支持5，10，30）
    DownloadType: type
  }
  // let routeUrl = this.$router.resolve({
  //   path: '/DownloadCenter',
  //   query: param
  // })
  // console.log(routeUrl.href)
  // window.open(routeUrl.href, '_blank')
  // window.open(window.Glob.ALL + "/" + this.xslxUrl);
}

// 打开图片
// const openImg = () => {
//   this.dialogVisible = true
// }

const coverChartResize = () => {
  setTimeout(() => {
    chart1.value.resize()
    chart2.value.resize()
  }, 0)
}

// 初始化echarts
const initEcharts = () =>{
  nextTick(() => {
    chart1.value = markRaw(myEcharts.init(document.getElementById('chart1')))
    chart2.value = markRaw(myEcharts.init(document.getElementById('chart2')))
    chart1.value.setOption(option)
    chart2.value.setOption(option)
  })
}

// 向外暴露的函数
defineExpose({
  showDialog
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    width="1523px"
    title="提示"
    center
  >
    <el-tabs
      v-model="activeName"
      type="card"
      class="production-statistics-tabs"
      @tab-click="handleClick"
    >
      <el-tab-pane
        label="报警策略设置"
        name="first"
      >
        <div class="alarm-strategy-box">
          <div class="btn-box">
            <div
              class="add-btn custom-button"
              @click="showFormDialog(0)"
            >
              添加报警策略
            </div>
          </div>
          <div class="table-box">
            <el-table
              :cell-style="cellStyle"
              :header-cell-style="headStyle"
              :data="tableData"
              max-height="320"
            >
              <el-table-column
                prop="date"
                label="传感器策略"
              />
              <el-table-column
                prop="name"
                label="一级报警值"
              />
              <el-table-column
                prop="address"
                label="二级报警值"
              />
              <el-table-column
                prop="address"
                label="操作"
              >
                <template #default="scope">
                  <div class="table-btn-box">
                    <div
                      class="update-btn"
                      @click="showFormDialog(1, scope.row)"
                    >
                      编辑
                    </div>
                    <div
                      class="delete-btn"
                      @click="deleteItem(scope.row)"
                    >
                      删除
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane
        label="历史数据"
        name="second"
      >
        <div class="history-data-box">
          <div class="time-select-box">
            <div class="date-picker-box">
              <el-form
                ref="coverRef"
                :inline="true"
                :model="formData"
                :rules="coverRules"
                class="demo-form-inline"
              >
                <el-form-item
                  v-if="isMore"
                  label="查询类型"
                >
                  <el-select
                    v-model.number="formData.Type"
                    size="small"
                  >
                    <el-option
                      v-for="item in searchTypeList"
                      :key="item.type"
                      :label="item.type"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-if="isMore"
                  label="时间间隔"
                >
                  <el-select
                    v-model.number="formData.timeInterval"
                    size="small"
                  >
                    <el-option
                      v-for="item in timeIntervalList"
                      :key="item.title"
                      :label="item.title"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="时间"
                >
                  <el-date-picker
                    v-model="time"
                    :clearable="false"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    type="datetimerange"
                    format="YYYY-MM-DD HH时"
                    value-format="YYYY-MM-DD HH:00:00"
                    sizi="small"
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button
                    v-if="!isMore"
                    type="primary"
                    size="small"
                    @click="isMore = true"
                  >
                    更多
                  </el-button>
                  <el-button
                    v-else
                    type="info"
                    size="small"
                    @click="isMore = false"
                  >
                    取消
                  </el-button>

                  <el-button
                    type="primary"
                    size="small"
                    @click="queryInfo"
                  >
                    查询
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    @click="exportXlsx('振动')"
                  >
                    导出
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    @click="exportXlsx('报告')"
                  >
                    分析报告
                  </el-button>
                </el-form-item>
              </el-form>
              <div class="cover-box">
                <p>温度表</p>
                <div
                  id="chart1"
                  ref="chart1"
                  style="width: 100%; height: 320px;"
                />
              </div>
              <div class="cover-box">
                <p>振动表</p>
                <div
                  id="chart2"
                  ref="chart2"
                  style="width: 100%; height: 320px;"
                />
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      v-model="formVisible"
      width="70%"
      :title="isAdd ? '添加信息' : '编辑信息'"
      append-to-body
    >
      <el-form
        class="formStyle"
        :model="fromList"
        :rules="rules"
        label-width="170px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="测点名称:"
              prop="name"
            >
              <el-input
                v-model="fromList.positionDescription"
                disabled
              />
            </el-form-item>

            <el-form-item
              label="一级报警值（最大值）:"
              prop="maxValue1"
            >
              <el-input v-model.number="fromList.maxValue1" />
            </el-form-item>
          </el-col>
          <el-col
            :span="8"
            :offset="4"
          >
            <el-form-item
              label="传感器类型:"
              prop="sensorType"
            >
              <el-select
                v-model="fromList.sensorType"
                placeholder="请选择传感器类型"
              >
                <el-option
                  v-for="item in sensorTypeList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item
              label="二级报警值（最大值）:"
              prop="maxValue2"
            >
              <el-input v-model.number="fromList.maxValue2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="form-btn-box">
          <el-button @click="cancellation">
            取 消
          </el-button>
          <el-button @click="determine">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<style scoped lang=scss>
.alarm-strategy-box {
  padding: 15px;
  border: 1px solid #dfdcdc;
}

.history-data-box {
  padding: 10px;
  border: 1px solid #dfdcdc;
}

.btn-box {
  height: 40px;
  margin-bottom: 10px;

  /* border: 1px solid red; */

  >div {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 124px;
    height: 40px;
  }
}

.table-btn-box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;

  >div {
    width: 56px;
    height: 28px;
    color: #fff;
    border-radius: 5px;

    /* background-color: red; */

    &:hover {
      cursor: pointer;
    }
  }

  .resetting-btn {
    width: 92px;
    height: 28px;
    margin-left: 10px;
    background-color: #a6a9ad;
  }

  .update-btn {
    background-color: #e6a23c;
  }

  .delete-btn {
    margin-left: 10px;
    background-color: #f56c6c;
  }
}

.form-btn-box {
  display: flex;
  justify-content: center;
  width: 100%;
}
</style>